/*
 * Copyright By Peak3
 * Copyright By c336bf6ff03a756989bb456b5b5e3271228d43ed38461eb5cb5755d17a2fc9b8
 * All rights reserved.
 *
 * If you are not the intended user, you are hereby notified that any use, disclosure, copying, printing, forwarding or
 * dissemination of this property is strictly prohibited. If you have got this file in error, delete it from your system.
 */

package com.vv.tools.modules.message.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vv.tools.common.message.Result;
import com.vv.tools.modules.message.model.MessageDTO;
import com.vv.tools.modules.message.model.request.MessageRequest;
import com.vv.tools.modules.message.service.MessageService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;

import java.util.List;
import java.util.Map;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 留言板控制器
 *
 * @author liwen
 */
@Slf4j
@RestController
@RequestMapping("/message")
@RequiredArgsConstructor
@Validated
@Tag(name = "留言板管理", description = "留言板相关接口")
public class MessageController {

    private final MessageService messageService;

    @GetMapping("/public/list")
    @Operation(summary = "获取公开留言列表", description = "获取已审核通过的留言列表，供前台展示")
    public Result<IPage<MessageDTO>> getPublicMessageList(
        @Parameter(description = "当前页", example = "1")
        @RequestParam(defaultValue = "1") Long current,
        @Parameter(description = "每页大小", example = "10")
        @RequestParam(defaultValue = "10") Long size) {

        IPage<MessageDTO> result = messageService.getPublicMessagePage(current, size);
        return Result.success(result);
    }

    @PostMapping("/submit")
    @Operation(summary = "提交留言", description = "用户提交新留言")
    public Result<Long> submitMessage(
        @Valid @RequestBody MessageRequest request,
        HttpServletRequest httpRequest) {

        try {
            Long messageId = messageService.submitMessage(request, httpRequest);
            return Result.success(messageId);
        } catch (Exception e) {
            log.error("提交留言失败", e);
            return Result.error("提交留言失败：" + e.getMessage());
        }
    }

    @PostMapping("/{id}/like")
    @Operation(summary = "点赞留言", description = "为留言点赞")
    public Result<Integer> likeMessage(
        @Parameter(description = "留言ID", required = true)
        @PathVariable @NotNull Long id) {

        try {
            Integer likeCount = messageService.likeMessage(id);
            return Result.success(likeCount);
        } catch (Exception e) {
            log.error("点赞失败", e);
            return Result.error("点赞失败：" + e.getMessage());
        }
    }

    @GetMapping("/admin/list")
    @Operation(summary = "管理员获取留言列表", description = "管理员查看所有留言")
    public Result<IPage<MessageDTO>> getMessageList(
        @Parameter(description = "当前页", example = "1")
        @RequestParam(defaultValue = "1") Long current,
        @Parameter(description = "每页大小", example = "10")
        @RequestParam(defaultValue = "10") Long size,
        @Parameter(description = "状态筛选：0-待审核，1-已通过，2-已拒绝")
        @RequestParam(required = false) Integer status,
        @Parameter(description = "关键词搜索")
        @RequestParam(required = false) String keyword) {

        IPage<MessageDTO> result = messageService.getMessagePage(current, size, status, keyword);
        return Result.success(result);
    }

    @GetMapping("/admin/{id}")
    @Operation(summary = "获取留言详情", description = "根据ID获取留言详情")
    public Result<MessageDTO> getMessageById(
        @Parameter(description = "留言ID", required = true)
        @PathVariable @NotNull Long id) {

        MessageDTO messageDTO = messageService.getMessageById(id);
        if (messageDTO == null) {
            return Result.error("留言不存在");
        }
        return Result.success(messageDTO);
    }

    @PostMapping("/admin/{id}/audit")
    @Operation(summary = "审核留言", description = "管理员审核留言")
    public Result<Boolean> auditMessage(
        @Parameter(description = "留言ID", required = true)
        @PathVariable @NotNull Long id,
        @Parameter(description = "审核状态：1-通过，2-拒绝", required = true)
        @RequestParam @NotNull Integer status,
        @Parameter(description = "回复内容")
        @RequestParam(required = false) String reply) {

        try {
            Boolean success = messageService.auditMessage(id, status, reply);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            log.error("审核留言失败", e);
            return Result.error("审核失败：" + e.getMessage());
        }
    }

    @PostMapping("/admin/{id}/top")
    @Operation(summary = "置顶/取消置顶留言", description = "管理员设置留言置顶状态")
    public Result<String> topMessage(
        @Parameter(description = "留言ID", required = true)
        @PathVariable @NotNull Long id,
        @Parameter(description = "是否置顶：0-否，1-是", required = true)
        @RequestParam @NotNull Integer isTop) {

        try {
            Boolean success = messageService.topMessage(id, isTop);
            if (success) {
                String message = isTop == 1 ? "置顶成功" : "取消置顶成功";
                return Result.success(message);
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("设置置顶失败", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/admin/{id}")
    @Operation(summary = "删除留言", description = "管理员删除留言")
    public Result<String> deleteMessage(
        @Parameter(description = "留言ID", required = true)
        @PathVariable @NotNull Long id) {

        try {
            Boolean success = messageService.deleteMessage(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除留言失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/admin/batch")
    @Operation(summary = "批量删除留言", description = "管理员批量删除留言")
    public Result<String> batchDeleteMessages(
        @Parameter(description = "留言ID列表", required = true)
        @RequestBody @NotEmpty List<Long> ids) {

        try {
            Boolean success = messageService.batchDeleteMessages(ids);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除留言失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    @GetMapping("/admin/stats")
    @Operation(summary = "获取留言统计", description = "获取留言统计信息")
    public Result<Map<String, Object>> getMessageStats() {

        try {
            Map<String, Object> stats = messageService.getMessageStats();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取留言统计失败", e);
            return Result.error("获取统计失败：" + e.getMessage());
        }
    }
}
